package edu.westga.cs3202.hw05;

import java.awt.*;
import javax.swing.*;

/**
 * A thread that draws a ball in a new position every few milliseconds.
 * 
 * @author Lewis Williams
 * @version 2011.02.28
 */
public class BallAnimation extends Thread {

	//The approximate time between redrawings.
	private final int sleepTime = 50;
	
	//The JPanel to be drawn on
	BallPanel panel = new BallPanel();

	/**
	 * Sets up the window.
	 */
	public BallAnimation() {
		JFrame frame = new JFrame("Ball Animation");
		frame.setPreferredSize(new Dimension(500, 535));
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		panel.setBackground(Color.WHITE);
		
		frame.getContentPane().add(panel);
		frame.pack();
		frame.setVisible(true);
	}

	/**
	 * Runs the thread approximately ever 50 milliseconds 150 times.
	 */
	public void run() {
		int count = 0;
		while (count < 150) {
			try {
				panel.repaint();
				Thread.sleep(sleepTime);
			} catch (InterruptedException e) {
				System.out.println("Ball draw terminated prematurely");
			}
 			count++;
		}
	}

	/**
	 * Inner class that is the panel the animation will take place on.
	 */
	class BallPanel extends JPanel {
		private static final long serialVersionUID = 1L;

		int x = 0;
		int y = 225;
		int mode = 1;

		/**
		 * Repaints the circle depending on it's position. 
		 */
		public void paintComponent(Graphics g){
			super.paintComponent(g);
			if(x - 100 == 0){
				mode = 1;
			}
			else if(x + 100 == 500){
				mode = 2;
			}
			else if(y + 100 == 500){
				mode = 3;
			}
			else if(y - 100 == 0){
				mode = 4;
			}
			//Down and to the right
			if (mode  == 1){
				g.setColor(Color.WHITE);
				g.fillOval(x, y, 100, 100);
				g.setColor(Color.BLACK);
				x = x + 5;
				y = y + 5;
				g.fillOval(x, y, 100, 100);
			}
			//Up and to the right
			else if(mode == 2){
				g.setColor(Color.WHITE);
				g.fillOval(x, y, 100, 100);
				g.setColor(Color.BLACK);
				x = x - 5;
				y = y - 5;
				g.fillOval(x, y, 100, 100);
			}
			//Up and to the left
			else if(mode == 3){
				g.setColor(Color.WHITE);
				g.fillOval(x, y, 100, 100);
				g.setColor(Color.BLACK);
				x = x + 5;
				y = y - 5;
				g.fillOval(x, y, 100, 100);
			}
			//Down and to the left
			else{
				g.setColor(Color.WHITE);
				g.fillOval(x, y, 100, 100);
				g.setColor(Color.BLACK);
				x = x - 5;
				y = y + 5;
				g.fillOval(x, y, 100, 100);
			}	
		}
	}
}
